package service

import (
	"dao"
	"pojo/form"
	"pojo/model"
	"constant"
	"pojo/vo"
)

/*
 * 用户服务
 */
type UserService struct {
	dao *dao.UserDao
}

/*
 * 构建用户服务层
 */
func NewUserService(userDao *dao.UserDao) *UserService {
	return &UserService{
		dao: userDao,
	}
}

/*
 * 用户明细服务
 */
type UserBalanceService struct {
	dao *dao.UserBalancesDao
}

/*
 * 构建用户明细服务层
 */
func NewUserBalanceService(userBalancesDao *dao.UserBalancesDao) *UserBalanceService {
	return &UserBalanceService{
		dao: userBalancesDao,
	}
}

/*
 * 添加客户信息
 */
func (this *UserService) InsertUser(userForm *form.UserForm) (*model.User, error) {
	_, errs := this.dao.GetUserOneByPhone(userForm.Phone)
	if errs != nil {
		user := &model.User{
			Name:     userForm.Name,
			Phone:    userForm.Phone,
			Img:      userForm.Img,
			Balance:  userForm.Balance,
			Referrer: userForm.Referrer,
		}
		_, err := this.dao.InsertUser(user)
		return user, err
	}
	return nil, constant.RECORD_EXISTS
}

/*
 * 通过ID查询客户信息
 */
func (this *UserService) FindUser(id uint64) (*model.User, error) {
	user, err := this.dao.FindUser(id)
	return user, err
}

/*
 * 通过电话号码查询客户信息
 */
func (this *UserService) GetUserByoPhone(phone string) (*model.User, error) {
	user, err := this.dao.GetUserOneByPhone(phone)
	return user, err
}

/*
 * 分页查询客户信息
 */
func (this *UserService) QueryUsers(query *form.UserPageQueryForm) *vo.TableVo {

	result := &vo.TableVo{}
	result.Code = constant.SUCCESS.Code
	result.Msg = constant.SUCCESS.Msg

	size, _ := this.dao.Count(query)
	result.Total = size

	if size > 0 {
		users, _ := this.dao.List(query)
		result.Items = users
	}

	return result
}

/*
 * 通过id删除单个客户信息
 */
func (this *UserService) DeleteUsers(id uint64) error {

	return this.dao.DeleteUser(id)
}

/*
 * 通过ID修改客户信息   如 余额变更，创建明细
 */
func (this *UserService) UpdateUserById(userForm *form.UserForm, id uint, balanceForm *form.UserBalanceForm) error {
	user := &model.User{
		Name:     userForm.Name,
		Phone:    userForm.Phone,
		Img:      userForm.Img,
		Balance:  userForm.Balance,
		Referrer: userForm.Referrer,
	}
	_, err := this.dao.UpdateUserOne(user, id)
	return err
}

/*
 * 创建客户账户明细
 */
func (this *UserBalanceService) InsertUserbalance(id uint, balanceForm *form.UserBalanceForm) error {
	userBalance := &model.UserBalanceStatement{
		UserId:            id,
		ChangeBalance:     balanceForm.ChangeBalance,
		ChangeBalanceType: balanceForm.ChangeBalanceType,
		Detail:            balanceForm.Detail,
	}
	_, err := this.dao.InsertUserBalances(userBalance);
	return err
}

/*
.* 通过客户ID分页查询客户账户明细
 */
func (this *UserBalanceService) GetUserbalanceList(user_id uint, page, limit int32) ([] *model.UserBalanceStatement, error) {
	userList, err := this.dao.GetUserBalancesList(page, limit, user_id)
	return userList, err
}
